const fs = require('fs');
const { pool } = require('../../db/index');
const Router = require('koa-router');
const router = new Router();
// 轮播图
router.get('/api/homepage/slides', async (ctx) => {
    try {
        const [imgs] = await pool.execute('SELECT * FROM homepage_slides');
        if (imgs.length > 0) {
            const responses = imgs.map(item => {
                // 提取相对路径
                const relativePath = item.image_url.replace(/^.*?imgs\//, '').replace(/\\/g, '/');
                // 使用传递过来的 serverUrl 拼接完整的图片 URL
                const fullImageUrl = `${module.exports.serverUrl}/${relativePath}`;
                return {
                    id: item.id,
                    image_url: fullImageUrl
                };
            });
            ctx.body = responses;
        } else {
            ctx.status = 404;
            ctx.body = { error: 'Image file not found' };
        }
    } catch (error) {
        console.error('获取首页轮播图失败', error);
        ctx.status = 500;
        ctx.body = { error: '获取首页轮播图失败' };
    }
});
// 热门书法家
router.get('/api/homepage/calligraphers', async (ctx) => {
  try {
      const [imgs] = await pool.execute('SELECT * FROM homepage_calligraphers');
      if (imgs.length > 0) {
          const responses = imgs.map(item => {
              const relativePath = item.image_url.replace(/^.*?imgs\//, '').replace(/\\/g, '/');
              const fullImageUrl = `${module.exports.serverUrl}/${relativePath}`;
              return {
                  id: item.id,
                  name: item.name,
                  image_url: fullImageUrl
              };
          });
          ctx.body = responses;
      } else {
          ctx.status = 404;
          ctx.body = { error: 'Image file not found' };
      }
  } catch (error) {
      ctx.status = 500;
      ctx.body = { error: '获取首页热门书法家失败' };
  }
});
// 热门字帖
router.get('/api/homepage/books', async (ctx) => {
  try {
      const [imgs] = await pool.execute('SELECT * FROM homepage_books');
      if (imgs.length > 0) {
          const responses = imgs.map(item => {
              const relativePath = item.image_url.replace(/^.*?imgs\//, '').replace(/\\/g, '/');
              const fullImageUrl = `${module.exports.serverUrl}/${relativePath}`;
              return {
                  id: item.id,
                  name: item.name,
                  image_url: fullImageUrl,
                  author: item.author
              };
          });
          ctx.body = responses;
      } else {
          ctx.status = 404;
          ctx.body = { error: 'Image file not found' };
      }
  } catch (error) {
      ctx.status = 500;
      ctx.body = { error: '获取首页热门字帖失败' };
  }
});
module.exports = router;